/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.breeze.dom;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

/**
 *
 * @author huateng
 */
public class IterateTag extends DefaultTag{
    
    public IterateTag(Node n){
        super(n);
    }
    
    public IterateTag(Node n,Object r){
        super(n,r);
    }
    
    @Override
    public String display(){
        Element e=(Element)node;
        String name=e.getAttribute("name");
        String alias=e.getAttribute("alias");
        String seprator=e.getAttribute("seprator");
        StringBuilder sb=new StringBuilder();
        NodeList list=e.getChildNodes();
        
        Integer size=(Integer)getValue(name+".size()");
        for(int i=0;i<size;i++){
            StringBuilder sbb=new StringBuilder();
            String expr=name+"["+i+"].";
            
            for(int j=0;j<list.getLength();j++){
                Node n=list.item(j);
                Text t=(Text)n;
                String str=t.getWholeText().trim();
                
                String ex="${"+alias;
                while(str.indexOf(ex)>-1){
                    int index=str.indexOf(ex);
                    int length;
                    for(length=index+2;;length++){
                        if(str.charAt(length)=='}')
                            break;
                    }
                    
                    String tmp=str.substring(index+2, length);
                    tmp=tmp.substring(tmp.indexOf('.')+1);
                    String exp=expr+tmp;
                    sbb.append(str.substring(0,index)).append(getValue(exp));
                    str=str.substring(length+1);
                }
                sbb.append(str);
            }
            if(i<size-1)
                sb.append(sbb.toString().trim()).append(seprator).append("\n");
            else
                sb.append(sbb.toString().trim());
        }
        
        return sb.toString();
    }
}
